<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑分类' : '新增分类'"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="category-form"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入分类名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="分类代码" prop="code">
        <el-input
          v-model="form.code"
          placeholder="请输入分类代码（英文字母和数字）"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="所属学科" prop="subjectId">
        <el-select
          v-model="form.subjectId"
          placeholder="请选择学科"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="subject in subjects"
            :key="subject.id"
            :label="subject.name"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio label="ACTIVE">激活</el-radio>
          <el-radio label="INACTIVE">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入分类描述（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { questionCategoryApi } from '@/api/questionCategories'

interface Props {
  modelValue: boolean
  category?: any
  subjects: any[]
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  category: null
})

const emit = defineEmits<Emits>()

const formRef = ref()
const loading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.category?.id)

const form = reactive({
  id: null,
  name: '',
  code: '',
  subjectId: undefined,
  status: 'ACTIVE',
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类代码', trigger: 'blur' },
    { 
      pattern: /^[A-Za-z0-9_]+$/, 
      message: '分类代码只能包含字母、数字和下划线', 
      trigger: 'blur' 
    },
    { min: 2, max: 20, message: '分类代码长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  subjectId: [
    { required: true, message: '请选择所属学科', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 初始化表单
const initForm = () => {
  if (props.category) {
    Object.assign(form, {
      id: props.category.id,
      name: props.category.name,
      code: props.category.code,
      subjectId: props.category.subjectId,
      status: props.category.status || 'ACTIVE',
      description: props.category.description || ''
    })
  } else {
    // 重置表单
    Object.assign(form, {
      id: null,
      name: '',
      code: '',
      subjectId: undefined,
      status: 'ACTIVE',
      description: ''
    })
  }
}

// 监听对话框显示状态
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    initForm()
    // 清除表单验证状态
    setTimeout(() => {
      formRef.value?.clearValidate()
    }, 100)
  }
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const submitData = { ...form }
    
    if (isEdit.value) {
      await questionCategoryApi.updateCategory(submitData.id, submitData)
      ElMessage.success('更新分类成功')
    } else {
      await questionCategoryApi.createCategory(submitData)
      ElMessage.success('创建分类成功')
    }
    
    emit('success')
  } catch (error: any) {
    console.error('提交失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('提交失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.category-form {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-radio) {
  margin-right: 0;
}
</style>